package com.itheima.mysecurity;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @auther 大雄
 * @create 2020-04-18 9:50
 */
@Component
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String error= URLEncoder.encode("用户名或密码错误", "UTF-8");
        Cookie cookie=new Cookie("error",error);
        cookie.setPath("/");
        cookie.setMaxAge(1);
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath()+"login.html");
    }
}
